<!--  -->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-alert
            title="添加商品信息"
            type="info"
            center
            show-icon
            :closable = "false"
            >
        </el-alert>
        <!-- 进度条 -->
        <el-steps align-center :active="activeIndex -0" finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <!-- 标签页 -->
        <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave = "beforeTabLeave" @tab-click = "tabClick">
            <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop = "goods_name">
                        <el-input v-model="form.goods_name" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop = "goods_price">
                        <el-input v-model="form.goods_price" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量"  prop = "goods_weight">
                        <el-input v-model="form.goods_weight" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量"  prop = "goods_number">
                        <el-input v-model="form.goods_number" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop = "goods_cat">
                        <!-- 级联选择器 -->
                        <el-cascader
                            size = "small"
                            clearable
                            change-on-select
                            expand-trigger="hover"
                            v-model="form.goods_cat"
                            :options="categorysList"
                            :props="defaultParams"
                            @change="handleChange"
                        ></el-cascader>
                    </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
                <el-form-item :label = "item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                    <el-checkbox-group v-model="item.attr_vals">
                        <el-checkbox :label="cb" v-for="(cb,index) in item.attr_vals" :key="index" border></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
                <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                    <el-input v-model="item.attr_vals" autocomplete="off"></el-input>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
                <!-- 图片上传 -->
                <el-upload
                    class="upload-demo"
                    action="http://127.0.0.1:8888/api/private/v1/upload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :headers="headerObj"
                    :on-success="handleSuccess"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
                <!-- 富文本编辑器 -->
                <quill-editor v-model="form.goods_introduce"></quill-editor>
                 <el-button type="primary" @click="addGoods" class="btnAdd">添加商品</el-button>
            </el-tab-pane>
        </el-tabs>
        </el-form>
        <!-- 图片预览的对话框 -->
        <el-dialog
            title="图片预览"
            :visible.sync="previewDialog"
            width="50%"
            >
            <img :src="previewPath" alt="" class="previewImg">
        </el-dialog>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import _ from 'lodash';
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
    //这里存放数据
        return {
            form:{
                goods_name:"",
                goods_cat:[],
                goods_price:"",
                goods_number:"",
                goods_weight:"",
                goods_introduce:"",
                pics:[],
                attrs:[],
                
            },
            rules:{
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ],
                goods_cat: [
                    { required: true, message: '请输入商品分类', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                goods_number: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' },
                ],
                goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' },
                ],
                goods_cat: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' },
                ],
            },
            active:0,
            categorysList:[],
            selectKeys:[],
            defaultParams:{
                  label:'cat_name',
                  value:'cat_id',
                  children:'children'
            },
            activeIndex:'0',
            manyTableData:[],
            onlyTableData:[],
            headerObj:{
                Authorization:window.sessionStorage.getItem("token")
            },
            previewPath:"",
            previewDialog:false
        };
    },
    //监听属性 类似于data概念
    computed: {
        cateId(){
            if (this.form.goods_cat.length ==3) {
                return this.form.goods_cat[2]
            }
            return null
        }
    },
    //监控data中的数据变化
    watch: {
        
    },
    //方法集合
    methods: {
        next(){
            //  if (this.active++ > 5) this.active = 0;
        },
        // 获取商品分类的数据
        async getGoodsCategorys(){
            const {data} = await this.$http({
                url:"categories",
            })
            this.categorysList = data.data;
            
        },
        handleChange(){
            // console.log(this.form.goods_cat);
            if (this.form.goods_cat.length !==3 ) {
                this.form.goods_cat = [];
            }
        },
        beforeTabLeave(currentName,oldName){
            if (this.form.goods_cat.length !==3  && oldName == 0){
                this.$message.error("请选择商品分类!");
                return false;
            }
        },
        async tabClick(){
            if (this.activeIndex == 1) {
                const {data} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{
                        sel:'many'
                    }
                });
                if (data.meta.status !== 200) {
                    return this.$message.error("获取失败!");
                }
                
                data.data.forEach( item => {
                     item.attr_vals = item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ")
                })
                
                this.manyTableData = data.data;
            }else if(this.activeIndex == 2){
                const {data} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{
                        sel:'only'
                    }
                });
                if (data.meta.status !== 200) {
                    return this.$message.error("获取失败!");
                }
                 this.onlyTableData = data.data;
            }
        },
        // 图片预览
        handlePreview(file){
            // console.log(file)
            this.previewPath = file.response.data.url;
            this.previewDialog = true;
        },
        // 图片上传成功
        handleSuccess(res){
          const picInfo = {
              pic:res.data.tmp_path
          };
          this.form.pics.push(picInfo);
        },
        handleRemove(file){
            const filePath = file.response.data.tmp_path;
            const i = this.form.pics.findIndex((x)=>{
                x.pic === filePath
            })
            this.form.pics.splice(i,1);
            console.log(this.form.pics);
        },
        // 添加商品
        addGoods(){
            // console.log(this.form);
            this.$refs.ruleForm.validate(async valid =>{
                if(!valid){
                    return this.$message.error("请填写必要的表单项!")
                }
                let newForm = _.cloneDeep(this.form);
                newForm.goods_cat = newForm.goods_cat.join(",");
                // console.log(newForm);
                // 处理动态参数
                this.manyTableData.forEach(item=>{
                    const newInfo = {
                        attr_id:item.attr_id,
                        attr_value:item.attr_vals.join(" ")
                    }
                    this.form.atts.push(newInfo)
                });
                // 处理静态属性
                this.onlyTableData.forEach(item=>{
                    const newInfo = {
                        attr_id:item.attr_id,
                        attr_value:item.attr_vals
                    }
                    this.form.atts.push(newInfo);
                });
                newForm.atts = this.form.atts;

                // 发送请求添加商品
                const {data} = await this.$http.post(`goods`,newForm)
                if (data.meta.status !=201 ) {
                    return this.$message.error("添加商品失败");
                }
                this.$message.success("添加商品成功");
                this.$router.push({name:"goods"})
            })
        }

    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.getGoodsCategorys()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        
    },
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-breadcrumb{
    margin-bottom: 15px;
    font-size: 14px;
}
.el-steps{
    margin: 15px 0;
}
.previewImg{
    width: 100%;
}
.btnAdd{
    margin-top: 15px;
}
</style>